"""
name: makeSet
author: robocky
date: 2016-12-29
description: Make a list of dictionary to describe instances.
"""


class DictSet(list):
    """List of dictionary"""
    def __init__(self, *keys):
        """Setup with dict's keys.
        And the end of keys must be the result out.
        """
        super(DictSet, self).__init__()
        self._keys = ()
        self._out_key = None
        self.set_dict_keys(keys)

    def set_dict_keys(self, keys):
        """Function of set dict's keys"""
        if keys is None:
            keys = ()
        self._keys = keys
        if len(self._keys) > 1:
            self._out_key = self._keys[-1]

    def get_keys(self):
        """Get keys."""
        return list(self._keys)

    def get_out_key(self):
        """Get out key."""
        return self._out_key

    def add_data(self, data: list=None):
        """Add a data list and turn to dict.
        The data's length must equal to dict's keys.
        """
        if len(data) is len(self._keys):
            self.append(dict(zip(self._keys, data)))
        else:
            print("Data's length is wrong, must be %d" % len(self._keys))
            print(self._keys)

    def print_attr(self):
        """Print attr of every instance's property."""
        for key in self._keys:
            print("%s:" % key, set(data[key] for data in self))

    def create_from_file(self, file_stream):
        """Create list with file."""
        # First line is keys
        keys = ''.join(file_stream.readline().split()).split(',')
        self.set_dict_keys(keys)
        for line in file_stream.readlines():
            self.add_data(''.join(line.split()).split(','))

    def split_data(self, key: str):
        """Split data into list of dictionary, use key."""
        if key in self._keys:
            attr_set = set(data[key] for data in self)
            result = {}
            for attr in attr_set:
                result[attr] = [data for data in self if data[key] == attr]
            return result
        else:
            print('The key %s is not a key of data.' % key)
            return {}

if __name__ == '__main__':
    with open('data.txt') as f:
        s = DictSet()
        s.create_from_file(f)
        for item in s:
            print(item)
        s.print_attr()
        print(s.split_data('Outlook'))
